/*
 * @Author: lyuan2018
 * @Date: 2019-08-21 10:02:20
 * @Last Modified by: lyuan2018
 * @Last Modified time: 2020-08-20 15:43:33
 * page: 添加联系人页面
 */
import React, { Component } from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import {
  WeaDialog,
  WeaLocaleProvider,
  WeaSearchGroup,
  WeaNewScroll,
  WeaCheckbox,
  WeaInput,
} from 'ecCom';
import { Row, Spin, Col, Button } from 'antd';
import { RenderForm } from '../emailSetting/util';

const getLabel = WeaLocaleProvider.getLabel;

@inject('emailContactStore')
@observer
class AddContact extends Component {
  constructor(props) {
    super(props);
    this.prefixCls = 'email-contact-addContact';
    this.state = {
      isAddGroup: false,
      newgroupvalue: '',
    };
    this.groups = [];
    this.initShow = true;
  }

  cancelNewGroup = () => {
    this.setState({ isAddGroup: false, newgroupvalue: '' });
  };

  addGroup = () => {
    const {
      emailContactStore: { newGroup, contactCondition },
    } = this.props;
    const { newgroupvalue } = this.state;
    let __this = this;
    newGroup(
      {
        groupName: newgroupvalue.trim(),
        operation: 'addOrThenMoveOrCopy',
        groupId: '0',
      },
      () => {
        __this.setState({ newgroupvalue: '' });
        contactCondition('', false);
      },
    );
  };

  onNewGroup = () => this.setState({ isAddGroup: true });

  renderAddGroup = () => {
    const { isAddGroup, newgroupvalue } = this.state;
    if (!isAddGroup) {
      return (
        <div className="new-group" onClick={this.onNewGroup}>
          <span className="icon-email-New-group" />
          <span>{getLabel(30131, '新建分组')} </span>
        </div>
      );
    }
    return (
      <div className="add-group">
        <div className="add-group-content">
          <WeaInput
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaInput@lazdqp`}
            placeholder={getLabel(30127, '分组名称')}
            value={newgroupvalue}
            onChange={v => this.setState({ newgroupvalue: v })}
          />
        </div>
        <div className="add-group-opt">
          <Button
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Button@m56fcw`}
            type="primary"
            disabled={newgroupvalue.trim() === ''}
            onClick={this.addGroup}
          >
            {getLabel(826, '确定')}
          </Button>
          <Button
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Button@8bokws`}
            onClick={this.cancelNewGroup}
          >
            {getLabel(201, '取消')}
          </Button>
        </div>
      </div>
    );
  };

  setGroups = () => {
    const {
      emailContactStore: { addContactGroups, addmailContact },
    } = this.props;
    let mailGroup =
      toJS(addmailContact.groups) &&
      toJS(addmailContact.groups).map(v => v.mailGroupId);
    let selectIds = this.groups
      .filter(v => v.isChecked === 1)
      .map(v => v.groupId);
    let condition_1 = item =>
      this.initShow && mailGroup && mailGroup.indexOf(item.groupId * 1) > -1;
    let condition_2 = item =>
      !this.initShow && selectIds.indexOf(item.groupId) > -1;
    let newGroup = toJS(addContactGroups).map((item) => {
      if (condition_1(item) || condition_2(item)) {
        return { ...item, isChecked: 1 };
      }
      return { ...item, isChecked: 0 };
    });
    return newGroup;
  };

  renderFormGroup = () => {
    this.groups = this.setGroups();
    return (
      <Row
        ecId={`${(this && this.props && this.props.ecId) || ''}_Row@ghrmyh`}
        className="wea-form-item clearfix wea-error email-form-formItem"
      >
        <Col
          ecId={`${(this && this.props && this.props.ecId) || ''}_Col@ib28bq`}
          span={8}
          className={`${this.prefixCls}-label`}
        >
          {getLabel(31458, '分组')}:
        </Col>
        <Col
          ecId={`${(this && this.props && this.props.ecId) || ''}_Col@9hpm1n`}
          span={16}
        >
          <div className={`${this.prefixCls}-group`}>
            <WeaNewScroll
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaNewScroll@j8nuq5`}
              height={155}
            >
              {this.groups &&
                this.groups.length > 0 &&
                this.groups.map(item => (
                  <div className={`${this.prefixCls}-group-item`}>
                    <WeaCheckbox
                      ecId={`${
                        (this && this.props && this.props.ecId) || ''
                      }_WeaCheckbox@v7pla1@${item.groupName}`}
                      content={item.groupName}
                      value={item.isChecked}
                      onChange={v => this.changeGroupSelect(v, item)}
                    />
                  </div>
                ))}
            </WeaNewScroll>
            {this.renderAddGroup()}
          </div>
        </Col>
      </Row>
    );
  };

  changeGroupSelect = (v, item) => {
    this.initShow = false;
    this.groups = this.groups.map((group) => {
      if (group.groupId === item.groupId) {
        return { ...item, isChecked: v * 1 };
      }
      return group;
    });
  };

  getForm = (form, fields) => {
    const { isFormInit } = form;
    let group = [];
    isFormInit &&
      fields &&
      fields.map((c, index) => {
        let items = [];
        if (index === 0) {
          c.items.map((field) => {
            items.push({
              com: RenderForm(form, {
                ...toJS(field),
                labelcol: 8,
                fieldcol: 16,
              }),
            });
          });
          items.push({ com: this.renderFormGroup() });
          group.push(
            <WeaSearchGroup
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaSearchGroup@y1mvyz@${c.title}`}
              className={`${this.prefixCls}-formGroup-0`}
              col={1}
              title={c.title}
              needTigger={true}
              showGroup={c.defaultshow}
              items={items}
            />,
          );
        } else if (index === 1) {
          c.items.map(field => items.push({ com: RenderForm(form, field) }));
          group.push(
            <WeaSearchGroup
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaSearchGroup@px213v@${c.title}`}
              className={`${this.prefixCls}-formGroup-1`}
              col={1}
              title={c.title}
              needTigger={true}
              showGroup={c.defaultshow}
              items={items}
            />,
          );
        }
      });
    return group;
  };

  onCancel = () => {
    const { emailContactStore, onCancel } = this.props;
    const { setStoreState, addContactForm } = emailContactStore;
    this.initShow = true;
    setStoreState({ editId: '' });
    addContactForm.resetForm();
    this.cancelNewGroup();
    if (onCancel && typeof onCancel === 'function') onCancel();
  };

  onSaveContact = () => {
    const { emailContactStore, onSubmit } = this.props;
    const { onSaveContact } = emailContactStore;
    let groups = this.groups.filter(v => v.isChecked === 1);
    groups = groups.map(v => v.groupId).join() || '';
    onSaveContact(
      { operation: 'addOrUpdateContact', groups },
      (data, isEdit) => {
        typeof onSubmit === 'function' && onSubmit(data, isEdit);
        this.onCancel();
      },
    );
  };

  // 添加联系人
  /*
    @params: 添加联系人方法传递参数
    @callback: initForm表单后回调函数
    @onHandleAdd: 点击添加联系人执行方法
  */
  addContacts = (params, callback) => {
    const { emailContactStore, onHandleAdd } = this.props;
    const { contactCondition, setStoreState } = emailContactStore;
    contactCondition(params, '', callback);
    setStoreState({ addContactTitle: getLabel(19956, '添加联系人') });
    if (onHandleAdd && typeof onHandleAdd === 'function') onHandleAdd();
  };

  render() {
    const { emailContactStore, visible } = this.props;
    const {
      addContactLoading,
      addContactForm,
      addContactFileds,
      addContactTitle,
    } = emailContactStore;
    const buttons = [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@6ubwdu@addcontactonsave`}
        type="primary"
        onClick={this.onSaveContact}
      >
        {getLabel(30986, '保存')}
      </Button>,
    ];
    const moreBtn = {
      datas: [
        {
          key: 'save',
          content: getLabel(30986, '保存'),
          disabled: false,
          onClick: this.onSaveContact,
        },
      ],
      collectParams: {
        favname: getLabel(572, '联系人'),
        favouritetype: 2,
        objid: 0,
        importantlevel: 1,
      },
    };
    return (
      <WeaDialog
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaDialog@r8mafr`}
        visible={visible || false}
        title={addContactTitle}
        icon={'icon-coms-email'}
        iconBgcolor="#a0b0ba"
        className={this.prefixCls}
        style={{ width: 696, height: 514 }}
        buttons={buttons}
        moreBtn={moreBtn}
        onCancel={this.onCancel}
        hasScroll
      >
        <Spin
          ecId={`${(this && this.props && this.props.ecId) || ''}_Spin@yqjn1c`}
          spinning={addContactLoading}
        >
          {this.getForm(addContactForm, addContactFileds)}
        </Spin>
      </WeaDialog>
    );
  }
}

/*
  外部调用方式：
  visible: must 控制弹窗显隐
  onHandleAdd: 点击添加联系人执行方法
  onCancel: 取消/关闭弹窗回调
  onSubmit: 保存回调
  open方法： 通过ref调用addContacts(params, callback)
*/

export default AddContact;
